"""
实时监控API接口
提供系统性能监控、流处理状态监控等功能
"""
from typing import List, Optional, Dict, Any
from datetime import datetime, timedelta
from fastapi import APIRouter, HTTPException, Depends, Query, Body
import logging

from services.real_time_performance_monitor import RealTimePerformanceMonitor
from services.real_time_stream_pipeline import RealTimeStreamPipeline
from services.camera_service import CameraService
from core.deps import get_current_user, get_db
from core.config_manager import get_config_manager, StreamProcessingConfig
from schemas.user import User
from sqlalchemy.orm import Session

logger = logging.getLogger(__name__)
router = APIRouter()

# 创建服务实例
performance_monitor = RealTimePerformanceMonitor()
stream_pipeline = RealTimeStreamPipeline()
config_manager = get_config_manager()


@router.get("/system/status")
async def get_system_status(
    current_user: User = Depends(get_current_user)
):
    """获取系统整体状态"""
    try:
        status = await performance_monitor.get_system_status()
        
        return {
            "timestamp": datetime.now(),
            "system_status": status,
            "uptime": await performance_monitor.get_system_uptime(),
            "version": "1.0.0"
        }
        
    except Exception as e:
        logger.error(f"获取系统状态失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取系统状态失败")


@router.get("/system/performance")
async def get_system_performance(
    duration_minutes: int = Query(60, ge=1, le=1440, description="时间范围(分钟)"),
    current_user: User = Depends(get_current_user)
):
    """获取系统性能指标"""
    try:
        end_time = datetime.now()
        start_time = end_time - timedelta(minutes=duration_minutes)
        
        metrics = await performance_monitor.get_performance_metrics(start_time, end_time)
        
        return {
            "time_range": {
                "start_time": start_time,
                "end_time": end_time,
                "duration_minutes": duration_minutes
            },
            "metrics": metrics
        }
        
    except Exception as e:
        logger.error(f"获取系统性能指标失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取系统性能指标失败")


@router.get("/system/alerts")
async def get_system_alerts(
    severity: Optional[str] = Query(None, description="告警级别"),
    limit: int = Query(100, ge=1, le=1000, description="返回数量限制"),
    current_user: User = Depends(get_current_user)
):
    """获取系统告警信息"""
    try:
        alerts = await performance_monitor.get_recent_alerts(severity, limit)
        
        return {
            "total_alerts": len(alerts),
            "alerts": alerts,
            "severity_filter": severity
        }
        
    except Exception as e:
        logger.error(f"获取系统告警失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取系统告警失败")


@router.get("/streams/overview")
async def get_streams_overview(
    current_user: User = Depends(get_current_user)
):
    """获取流处理概览"""
    try:
        overview = await stream_pipeline.get_processing_overview()
        
        return {
            "timestamp": datetime.now(),
            "overview": overview
        }
        
    except Exception as e:
        logger.error(f"获取流处理概览失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取流处理概览失败")


@router.get("/streams/performance")
async def get_streams_performance(
    camera_ids: Optional[List[str]] = Query(None, description="摄像头ID列表"),
    current_user: User = Depends(get_current_user)
):
    """获取流处理性能指标"""
    try:
        if camera_ids:
            # 获取指定摄像头的性能指标
            performance_data = {}
            for camera_id in camera_ids:
                metrics = await stream_pipeline.get_camera_performance_metrics(camera_id)
                if metrics:
                    performance_data[camera_id] = metrics
        else:
            # 获取所有摄像头的性能指标
            performance_data = await stream_pipeline.get_all_performance_metrics()
        
        return {
            "timestamp": datetime.now(),
            "camera_count": len(performance_data),
            "performance_data": performance_data
        }
        
    except Exception as e:
        logger.error(f"获取流处理性能指标失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取流处理性能指标失败")


@router.get("/streams/health")
async def get_streams_health(
    current_user: User = Depends(get_current_user)
):
    """获取流健康状态"""
    try:
        health_status = await stream_pipeline.get_streams_health_status()
        
        return {
            "timestamp": datetime.now(),
            "health_status": health_status
        }
        
    except Exception as e:
        logger.error(f"获取流健康状态失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取流健康状态失败")


@router.get("/ai/performance")
async def get_ai_performance(
    algorithm: Optional[str] = Query(None, description="AI算法名称"),
    current_user: User = Depends(get_current_user)
):
    """获取AI算法性能指标"""
    try:
        performance_data = await performance_monitor.get_ai_performance_metrics(algorithm)
        
        return {
            "timestamp": datetime.now(),
            "algorithm_filter": algorithm,
            "performance_data": performance_data
        }
        
    except Exception as e:
        logger.error(f"获取AI性能指标失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取AI性能指标失败")


@router.get("/ai/statistics")
async def get_ai_statistics(
    duration_hours: int = Query(24, ge=1, le=168, description="统计时间范围(小时)"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取AI算法统计信息"""
    try:
        camera_service = CameraService(db)
        ai_stats = camera_service.get_ai_algorithm_statistics()
        
        # 获取处理统计
        end_time = datetime.now()
        start_time = end_time - timedelta(hours=duration_hours)
        processing_stats = await performance_monitor.get_ai_processing_statistics(start_time, end_time)
        
        return {
            "time_range": {
                "start_time": start_time,
                "end_time": end_time,
                "duration_hours": duration_hours
            },
            "algorithm_usage": ai_stats,
            "processing_statistics": processing_stats
        }
        
    except Exception as e:
        logger.error(f"获取AI统计信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取AI统计信息失败")


@router.get("/resources/usage")
async def get_resource_usage(
    current_user: User = Depends(get_current_user)
):
    """获取资源使用情况"""
    try:
        resource_usage = await performance_monitor.get_resource_usage()
        
        return {
            "timestamp": datetime.now(),
            "resource_usage": resource_usage
        }
        
    except Exception as e:
        logger.error(f"获取资源使用情况失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取资源使用情况失败")


@router.get("/config/stream-processing")
async def get_stream_processing_config(
    current_user: User = Depends(get_current_user)
):
    """获取流处理配置"""
    try:
        config = config_manager.get_stream_processing_config()
        
        return {
            "config": config.dict(),
            "timestamp": datetime.now()
        }
        
    except Exception as e:
        logger.error(f"获取流处理配置失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取流处理配置失败")


@router.put("/config/stream-processing")
async def update_stream_processing_config(
    config: StreamProcessingConfig = Body(..., description="流处理配置"),
    current_user: User = Depends(get_current_user)
):
    """更新流处理配置"""
    try:
        success = await config_manager.update_stream_processing_config(config, current_user.username)
        
        if not success:
            raise HTTPException(status_code=400, detail="更新配置失败")
        
        return {
            "message": "流处理配置更新成功",
            "config": config.dict(),
            "updated_by": current_user.username,
            "timestamp": datetime.now()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新流处理配置失败: {str(e)}")
        raise HTTPException(status_code=500, detail="更新流处理配置失败")


@router.get("/config/summary")
async def get_config_summary(
    current_user: User = Depends(get_current_user)
):
    """获取配置摘要"""
    try:
        summary = config_manager.get_config_summary()
        
        return {
            "config_summary": summary,
            "timestamp": datetime.now()
        }
        
    except Exception as e:
        logger.error(f"获取配置摘要失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取配置摘要失败")


@router.get("/config/history")
async def get_config_change_history(
    limit: int = Query(50, ge=1, le=500, description="返回数量限制"),
    current_user: User = Depends(get_current_user)
):
    """获取配置变更历史"""
    try:
        history = config_manager.get_change_history(limit)
        
        return {
            "total_changes": len(history),
            "changes": [change.dict() for change in history],
            "limit": limit
        }
        
    except Exception as e:
        logger.error(f"获取配置变更历史失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取配置变更历史失败")


@router.post("/reports/performance")
async def generate_performance_report(
    report_config: Dict[str, Any] = Body(..., description="报告配置"),
    current_user: User = Depends(get_current_user)
):
    """生成性能报告"""
    try:
        report = await performance_monitor.generate_performance_report(report_config)
        
        return {
            "report": report,
            "generated_by": current_user.username,
            "timestamp": datetime.now()
        }
        
    except Exception as e:
        logger.error(f"生成性能报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail="生成性能报告失败")


@router.get("/reports/daily")
async def get_daily_report(
    date: Optional[str] = Query(None, description="日期 (YYYY-MM-DD)"),
    current_user: User = Depends(get_current_user)
):
    """获取日报告"""
    try:
        if date:
            report_date = datetime.strptime(date, "%Y-%m-%d").date()
        else:
            report_date = datetime.now().date()
        
        report = await performance_monitor.get_daily_report(report_date)
        
        return {
            "report_date": report_date,
            "report": report
        }
        
    except ValueError:
        raise HTTPException(status_code=400, detail="日期格式错误，请使用 YYYY-MM-DD 格式")
    except Exception as e:
        logger.error(f"获取日报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取日报告失败")


@router.post("/system/health-check")
async def perform_system_health_check(
    current_user: User = Depends(get_current_user)
):
    """执行系统健康检查"""
    try:
        health_check_result = await performance_monitor.perform_health_check()
        
        return {
            "health_check": health_check_result,
            "checked_by": current_user.username,
            "timestamp": datetime.now()
        }
        
    except Exception as e:
        logger.error(f"系统健康检查失败: {str(e)}")
        raise HTTPException(status_code=500, detail="系统健康检查失败")


@router.post("/system/optimize")
async def optimize_system_performance(
    optimization_config: Dict[str, Any] = Body(..., description="优化配置"),
    current_user: User = Depends(get_current_user)
):
    """优化系统性能"""
    try:
        optimization_result = await performance_monitor.optimize_system_performance(optimization_config)
        
        return {
            "optimization_result": optimization_result,
            "optimized_by": current_user.username,
            "timestamp": datetime.now()
        }
        
    except Exception as e:
        logger.error(f"系统性能优化失败: {str(e)}")
        raise HTTPException(status_code=500, detail="系统性能优化失败")